package com.dian.diabetes.service;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.dian.diabetes.tool.Preference;
import com.dian.diabetes.utils.CheckUtil;
import com.dian.diabetes.utils.ContantsUtil;
import com.dian.diabetes.utils.HttpServiceUtil;

public class TokenService extends Service {
	
	private String Token="";
	private Preference preference;
	private List<RongIMClient.UserInfo> list = new ArrayList<RongIMClient.UserInfo>();
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == 0){
				Toast.makeText(getApplicationContext(), "获取数据失败",Toast.LENGTH_SHORT).show();
			}else if(msg.what == 1){
				RongIM.setGetFriendsProvider(new RongIM.GetFriendsProvider() {
		            @Override
		            public List<RongIMClient.UserInfo> getFriends() {
		                return list;
		            }
		        }); 
			}else if(msg.what == 2){
				try {
					RongIM.connect(Token, new RongIMClient.ConnectCallback() {

						@Override
						public void onSuccess(String s) {
							Log.e("token", Token);
							Log.e("Connect:", "Connect successfully.");
							preference.putString("mytoken", Token);  //保存获取的token
							stopSelf();
						}

						@Override
						public void onError(ErrorCode errorCode) {
							Log.e("Connect:", "Connect failed.");
							stopSelf();
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		RongIM.init(this); 
		preference = Preference.instance(getApplicationContext());
		Token = preference.getString(ContantsUtil.TOKEN);
		RongIM.setGetUserInfoProvider(new RongIM.GetUserInfoProvider() {
            @Override
            public RongIMClient.UserInfo getUserInfo(String userId) {
                return getUserInfoFromLocalCache(userId); 
            }
        }, false);
		getFriendsFromServer();
		if(!Token.equals("")){
			handler.sendEmptyMessage(2);
		}else getTokenFromAppServer();
		return START_NOT_STICKY;
	}
	
	
	protected void getFriendsFromServer() {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", ContantsUtil.curInfo.getMid());
		HttpServiceUtil.request(ContantsUtil.URL_GET_FRIENDS, "post", params, new HttpServiceUtil.CallBack() {
			
			@Override
			public void callback(String json) {
				try {
					JSONArray jsonArray = new JSONObject(json).optJSONArray("data");
					list.clear();
					for(int i=0;i<jsonArray.length();i++){
						JSONObject jsonObject= jsonArray.getJSONObject(i);
						String id = jsonObject.getString("userId");
						String name = jsonObject.getString("userName");
						String avatar = jsonObject.getString("portraitUri");
						RongIMClient.UserInfo user = new RongIMClient.UserInfo(id, name, avatar);
						list.add(user);
					}
					handler.sendEmptyMessage(1);
				} catch (JSONException e) {
					handler.sendEmptyMessage(0);
					e.printStackTrace();
				}
			}
		});
	}

	private RongIMClient.UserInfo getUserInfoFromLocalCache(String userId) {
		RongIMClient.UserInfo  userInfo = null;
		if(userId.equals(ContantsUtil.curInfo.getMid()+""))
		userInfo = new RongIMClient.UserInfo(ContantsUtil.curInfo.getMid()+"", ContantsUtil.curInfo.getNick_name(), ContantsUtil.curInfo.getAvatar());
		return userInfo;
	}

	private void getTokenFromAppServer() {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", ContantsUtil.curInfo.getMid());
		params.put("userName", ContantsUtil.curInfo.getNick_name());
		params.put("portraitUri", ContantsUtil.curInfo.getAvatar());
		HttpServiceUtil.request(ContantsUtil.URL_GET_TOKEN, "post", params, new HttpServiceUtil.CallBack() {
			
			@Override
			public void callback(String json) {
				try {
					JSONObject jsonObject = new JSONObject(json).optJSONObject("data");
					String alldata = jsonObject.optString("result");
					Token = new JSONObject(alldata).optString("token");
					handler.sendEmptyMessage(2);
				} catch (JSONException e) {
					handler.sendEmptyMessage(0);
					e.printStackTrace();
				}
			}
		});
	}
}
